import socket
import threading
from cryptography.fernet import Fernet

# 从文件中加载密钥
def load_key():
    with open("secret.key", "rb") as key_file:
        return key_file.read()

key = load_key()
cipher = Fernet(key)

# 输入服务器的 IP 和端口
HOST = 'IP'  # 替换为服务器的实际 IP 地址
PORT = 12345  # 与服务器端一致的端口

# 创建一个 TCP/IP 套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

# 接收消息的函数
def receive():
    while True:
        try:
            # 接收并解密从服务器发送的消息
            encrypted_message = client_socket.recv(1024)
            message = cipher.decrypt(encrypted_message).decode('utf-8')
            print(message)
        except:
            # 出现错误则关闭连接
            print("An error occurred!")
            client_socket.close()
            break

# 发送消息的函数
def send():
    while True:
        message = input("")
        encrypted_message = cipher.encrypt(f'{nickname}: {message}'.encode('utf-8'))
        client_socket.send(encrypted_message)

# 输入客户端的昵称
nickname = input("Choose your nickname: ")
client_socket.send(cipher.encrypt(nickname.encode('utf-8')))

# 启动接收消息的线程
receive_thread = threading.Thread(target=receive)
receive_thread.start()

# 启动发送消息的线程
send_thread = threading.Thread(target=send)
send_thread.start()
